import os
import shutil
from PIL import Image, ImageSequence

import numpy as np


# 清空缓存文件temp问价夹
def del_file(path_data):
    for i in os.listdir(path_data):  # os.listdir(path_data)#返回一个列表，里面是当前目录下面的所有东西的相对路径
        file_data = path_data + "\\" + i  # 当前文件夹的下面的所有东西的绝对路径
        if os.path.isfile(file_data) == True:  # os.path.isfile判断是否为文件,如果是文件,就删除.如果是文件夹.递归给del_file.
            os.remove(file_data)
        else:
            del_file(file_data)


# 修改gif图品大小格式
def pictool(newfile):
    print("读取文件" + newfile)
    # 读取图片内容
    pic = Image.open(newfile)
    width, height = pic.size
    # print("宽:", width, "高:", height)
    if width > height:
        x1 = (width - height) // 2
        y1 = 0
        x2 = (width - height) // 2 + height
        y2 = height
        box = (x1, y1, x2, y2)
        # print("裁切范围", x1, y1, x2, y2)
        newp = pic.crop(box)
        # 保存文件
        newp.save(newfile)

    elif width < height:
        a1 = 0
        b1 = (height - width) // 2
        a2 = width
        b2 = (height - width) // 2 + width
        box = (a1, b1, a2, b2)
        # print("裁切范围", a1, b1, a2, b2)
        newp = pic.crop(box)
        newp.save(newfile)


# Gif主操作函数
def gifoperat(readfile):
    # list所有读取文件
    print("读取文件：" + readfile)
    oriGif = Image.open(readfile)
    lifeTime = oriGif.info['duration']
    imgList = []
    newgif = []
    for i in ImageSequence.Iterator(oriGif):
        # print(i.copy())
        imgList.append(i.copy())
    for index, f in enumerate(imgList):
        f.save(nowdir + "\\temp\\%d.png" % index)

    os.chdir(temproute)
    tempdirslist = os.listdir(temproute)
    print("获取当前所有文件名排序位为:")
    print(tempdirslist)

    print("执行匿名排序.", end="")
    tempdirslist.sort(key=lambda x: int(x[:-4]))  ##文件名按数字排序
    tempdirslistsort = len(tempdirslist)
    print(tempdirslist)

    # 判断非空，批量执行裁剪保存在覆盖temp
    if tempdirslist:
        print("文件目录存在")
        print(tempdirslistsort)
        for zhenimage in tempdirslist:
            pictool(zhenimage)

    print(os.getcwd())
    print("当前操作文件:" + readfile)

    # 保存图片文件内容
    for image in tempdirslist:
        newpic = Image.open(image)
        newgif.append(newpic)
        newgif[0].save(gifroute + readfile, 'gif', save_all=True, append_images=newgif[1:], loop=0, duration=lifeTime)

    path_data = os.getcwd()
    print("即将清空缓存temp" + temproute)
    del_file(path_data)
    print("清空完毕" + temproute)
    os.chdir(gifroute)


# 获取当前路径
global nowdir
nowdir = os.getcwd()

# GIF路径
global gifroute
gifroute = nowdir + "\\gif"
print("GIF路径为" + gifroute)

# 缓存路径
global temproute
temproute = nowdir + "\\temp"
print("temp路径为" + temproute)

nowdir = os.getcwd()
print("当前路径为:" + nowdir)
os.chdir(gifroute)
print("当前路径为:" + os.getcwd())
dirs = os.listdir(gifroute)
print("即将操作gif列表：")
print(dirs)
count = 0
for file in dirs:
    gifoperat(file)
